# -*- coding:utf-8 -*-
import json
import urllib2

DOCKER = False
# DOCKER = True
IPADDR = "127.0.0.1"


def cfg_timedb(cmd):
    if DOCKER:
        return "http://%s/timedb/%s" % (IPADDR, cmd)
    return "http://127.0.0.1:9993/timedb/%s" % cmd


def put_json(url, v):
    value = json.dumps(v)
    req = urllib2.Request(url, value, {'Content-Type': 'application/json'})
    try:
        response = urllib2.urlopen(req)
    except urllib2.HTTPError as e:
        return e.code

    return response.read()


def get_json(url, data):
    respone = put_json(url, data)
    return json.loads(respone)


if __name__ == '__main__':
    tab = "stnstatus"

    tag = {
            "esn",
            "line",
            "psn",
            "ti",
            "usn",
            "wsn",
            "msn_1",
            }

    tag_merge = {
            "msn_1": "msn",
            }

    field_merge = {
            }

    url = cfg_timedb("get")
    ret = get_json(url, {
        "n": tab,
        "tm": True,
        "obj": "*",
    })

    data = ret[tab]["data"]

    wt = []
    l = 0
    tmp = []

    for d in data:
        dk = {}
        dv = {}

        for k, v in d.items():
            if k == "time":
                continue

            if k in tag:
                if k in tag_merge:
                    dk[tag_merge[k]] = v
                else:
                    dk[k] = v
            else:
                if k in field_merge:
                    dv[field_merge[k]] = v
                else:
                    dv[k] = v

        tmp.append({
            "tm": d["time"],
            "k": dk,
            "v": dv,
            })

        l += 1
        if l > 2000:
            wt.append(tmp)
            tmp = []

    if len(tmp) > 0:
        wt.append(tmp)

    url = cfg_timedb("md")

    for d in wt:
        ret = get_json(url, {
            "n": "%s_bk" % tab,
            "data": d
        })
        print(ret)

    print("stop influxdb")
    print("cd /var/lib/influxdb/")
    print("find -name *.idx | xargs rm")
    print("SELECT * INTO new_measurement FROM measurement GROUP BY *")
